// src/middleware/jwt.middleware

import { Inject, Middleware } from '@midwayjs/decorator';
import { Context, NextFunction } from '@midwayjs/koa';
// import { httpError } from '@midwayjs/core';
import { JwtService } from '@midwayjs/jwt';

@Middleware()
export class JwtMiddleware {
  @Inject()
  jwtService: JwtService;

  public static getName(): string {
    return 'jwt';
  }

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      let token: any = ctx.headers['token'];
      // 判断下有没有校验信息
      if (!token) {
        // throw new httpError.UnauthorizedError();
        return returnBody();
      }

      try {
        token = await this.jwtService.verify(token, {
          complete: true,
        });
      } catch (error) {
        return returnBody();
      }
      return await next();
    };
  }

  ignore(ctx: Context): boolean {
    const pathArr = [
      '/api/user/register',
      '/api/user/login',
      '/api/test',
      '/api/article/find',
      '/api/article/finds',
      '/api/article/findHots',
      '/api/common/getCode',
      '/api/type/finds',
    ];
    // 下面的路由将忽略此中间件
    return pathArr.indexOf(ctx.path) >= 0;
  }
}

function returnBody() {
  return {
    data: '',
    code: 400,
    message: '请先登录!',
  };
}
